<template>
    <div class="profile-page">
        <section class="section-profile-cover section-shaped my-0">
            <div class="shape shape-style-1 shape-primary shape-skew alpha-4">
                <span></span>
                <span></span>
                <span></span>
                <span></span>
                <span></span>
                <span></span>
                <span></span>
            </div>
        </section>
        <section class="section section-skew">
            <div class="container">
                <card shadow class="card-profile mt--300" no-body>
                    <div class="px-4">
                        <div class="row justify-content-center">
                            <div class="col-lg-3 order-lg-2">
                                <div class="card-profile-image">
                                    <a href="#">
                                        <img :src="userIcon" class="rounded-circle">
                                    </a>
                                </div>
                            </div>
                            <div class="col-lg-4 order-lg-3 text-lg-right align-self-lg-center">
                                <div class="card-profile-actions py-4 mt-lg-0 justify-content-center">
                                    <base-button @click="open('check-manage')" v-if="isSelf && !isAdmin" type="info" size="sm" class="mr-4">订单管理</base-button>
                                    <base-button type="default" size="sm" v-if="isSelf || isAdmin" v-b-modal.modal-1>信息修改</base-button>
                                    <b-modal id="modal-1" title="信息修改" >
                                        <form role="form">
                                            <div class="justify-content-center">
                                                <b-form-file
                                                v-model="ruleForm.file"
                                                :state="Boolean(ruleForm.file)"
                                                placeholder="请选择头像或拖动头像到此"
                                                drop-placeholder="放下"
                                                accept="image/*"
                                                class="mb-3"
                                                ></b-form-file>
                                                <base-input v-model="ruleForm.name" type="text" placeholder="昵称" addon-left-icon="ni ni-single-02"></base-input>
                                                <base-input v-model="ruleForm.age" type="number" @input="oninputNM" placeholder="年龄" addon-left-icon="ni ni-circle-08"></base-input>
                                                <base-input v-model="ruleForm.district" type="text" placeholder="城市" addon-left-icon="ni ni-world"></base-input>
                                                <base-input v-model="ruleForm.province" type="text" placeholder="省份" addon-left-icon="ni ni-world-2"></base-input>
                                                <base-input v-model="ruleForm.phoneNum"
                                                            :error="phoneCheckError"
                                                            @change="phoneCheckError=''"
                                                            placeholder="电话"
                                                            addon-left-icon="ni ni-mobile-button"></base-input>
                                                <textarea v-model="ruleForm.personIntro" class="form-control form-control-alternative mb-3" rows="3" placeholder="个人描述"></textarea>
                                                <div class="row mb-3">
                                                    <base-button @click="submitChange" type="primary" class="contentDiv">{{submitText}}</base-button>
                                                </div>
                                                <div v-if="showSaveSuccess" class="row justify-content-center">
                                                    <small class="text-success">保存成功</small>
                                                    <i class="fa fa-check"></i>
                                                </div>
                                                <div v-if="showSaveFail" class="row justify-content-center">
                                                    <small class="text-danger">保存失败</small>
                                                    <i class="fa fa-times"></i>
                                                </div>
                                            </div>

                                        </form>
                                        <template slot="modal-footer" slot-scope="{ok}">
                                            <!-- Emulate built in modal footer ok and cancel button actions -->
                                            <b-button size="sm" variant="success" @click="myOk">
                                                完成
                                            </b-button>
                                        </template>
                                    </b-modal>
                                </div>
                            </div>
                            <div class="col-lg-4 order-lg-1">
                                <div class="card-profile-stats d-flex justify-content-center">
                                    <div>
                                        <span class="heading">{{orders.length}}</span>
                                        <span class="description">全部</span>
                                    </div>
                                    <div> 
                                        <span class="heading">{{successNum}}</span>
                                        <span class="description">已完成</span>
                                    </div>
                                    <div> 
                                        <span class="heading">{{failNum}}</span>
                                        <span class="description">未完成</span>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="text-center mt-5">
                            <h3>{{userInfo.name}}
                                <span v-if="userInfo.age" class="font-weight-light">, {{userInfo.age}}</span>
                            </h3>
                            <div class="h6 font-weight-300"><i class="ni location_pin mr-2"></i>{{userDistrict}},
                                {{userProvince}}</div>
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="h6 mt-4" style="text-align:right;"><i class="ni ni-email-83 business_briefcase-24 mr-2"></i>邮箱：</div>
                                </div>
                                <div class="col-md-6">
                                    <div class="h6 mt-4" style="text-align: left;"><i class="ni business_briefcase-24 mr-2"></i>{{userInfo.email}}</div>
                                </div>
                            </div>
                            <div v-if="userInfo.phoneNum" class="row">
                                <div class="col-md-6">
                                    <div class="h6" style="text-align:right"><i class="ni ni-mobile-button education_hat mr-2"></i>电话：</div>
                                </div>
                                <div class="col-md-6">
                                    <div class="h6" style="text-align:left"><i class="ni education_hat mr-2"></i>{{userInfo.phoneNum}}</div>
                                </div>
                            </div>
                        </div>
                        <div class="mt-5 py-5 border-top text-center">
                            <div class="row justify-content-center">
                                <div class="col-lg-9">
                                    <strong>个人描述</strong>
                                    <p v-if="userInfo.personIntro">{{userInfo.personIntro}}</p>
                                    <p v-else>TA还没有填写个人描述:)</p>
                                </div>
                            </div>
                        </div>
                    </div>
                </card>
            </div>
        </section>
    </div>
</template>
<script>
import {checkCookie, userOrders, myInfo, upload, changeUserInfo,getUserInfom,adminChangeUserInfo,getUserInfo} from "../api";
import {checkPhoneNum} from "../utils/regjudge";
import {setStore} from "../utils/storage";

export default {
    data(){
        return {
            // userIcon: 'img/theme/team-4-800x800.jpg',
            role: 0,
            orders: '',
            userInfo: '',
            userDistrict: '海淀',
            userProvince: '北京',
            ruleForm:{
                file: null,
                name: '',
                age: '',
                district: '',
                province: '',
                phoneNum: '',
                personIntro: ''
            },
            showSaveSuccess: false,
            showSaveFail: false,
            phoneCheckError: '',
            submitText: '保存',
            successNum: 0,
            failNum: 0,
            isSelf:false,
            isAdmin:false
        }
    },
    methods: {
        myOk(){
            this.$router.go(0);
        },
        open (t) {
            this.$router.push({name: t});
        },
        oninputNM(){
            // 非负整数
            let value = this.ruleForm.age;
            this.ruleForm.age = (value.match(/^\d*(\.?)/g)[0]) || null;
        },
        submitChange(){
            this.showSaveSuccess = false;
            this.showSaveFail = false;
            this.submitText = '保存中……';
            let param = {};
            if (this.ruleForm.phoneNum)
            {
                if (checkPhoneNum(this.ruleForm.phoneNum))
                {
                    param.phoneNum=this.ruleForm.phoneNum;
                } else {
                    this.phoneCheckError = "请填写正确的电话号码!";
                    this.submitText = '保存';
                    return false;
                }
            }
            if (this.ruleForm.name)
            {
                param.name= this.ruleForm.name;
            }
            if (this.ruleForm.age)
            {
                param.age=this.ruleForm.age;
            }
            if (this.ruleForm.district)
            {
                param.district=this.ruleForm.district;
            }
            if (this.ruleForm.province)
            {
                param.province=this.ruleForm.province;
            }
            if (this.ruleForm.personIntro)
            {
                param.personIntro=this.ruleForm.personIntro;
            }
            new Promise((resolve) => {
                if (this.ruleForm.file)
                {
                    let formData = new FormData();
                    formData.append('file', this.ruleForm.file);
                    upload(formData).then(res=>{
                        if (res.code === "1"){
                            console.log("imgaddr", res.data);
                            param.avatar= res.data;
                            resolve();
                        } else {
                            this.showSaveFail = true;
                            this.ruleForm.file = null;
                            this.submitText = '保存';
                            return false;
                        }
                    })
                } else {
                    resolve();
                }
            }).then(()=>{
                param.role=this.role;
                console.log("toupload", param);
                if(this.role == "admin"&& this.$route.params.uid !== undefined){
                    param.uid = this.$route.params.uid;
                    adminChangeUserInfo(param).then(res => {
                        if (res.code === "1"){
                            this.showSaveSuccess = true;
                            this.submitText = '保存';
                            return true;
                        } else {
                            this.showSaveFail = true;
                            this.submitText = '保存';
                            return false;
                        }
                    }).catch( err => {
                        console.log("profile.submitChange.adminChangeUserInfo:", err);
                        this.showSaveFail = true;
                        this.submitText = '保存';
                        return false;
                    });
                }
                else{
                    changeUserInfo(param).then(res => {
                        if (res.code === "1"){
                            this.showSaveSuccess = true;
                            this.submitText = '保存';
                            return true;
                        } else {
                            this.showSaveFail = true;
                            this.submitText = '保存';
                            return false;
                        }
                    }).catch( err => {
                        console.log("profile.submitChange.changeUserInfo:", err);
                        this.showSaveFail = true;
                        this.submitText = '保存';
                        return false;
                    });
                }
            }).catch( err => {
                console.log("profile.submitChange.upload:", err);
                this.showSaveFail = true;
                this.submitText = '保存';
                return false;
            });
        }
    },
    watch:{
        userInfo(newValue){
            if (newValue.district){
                this.userDistrict = newValue.district;
            }
            if (newValue.province){
                this.userProvince = newValue.province;
            }
        }
    },
    created() {
        checkCookie()
        .then(res => {
            if (res.code === "1"){
                this.role = res.data;
                console.log(this.$route.params.uid);
                if (this.$route.params.uid === undefined){
                    //获取自己的用户信息 显示两个button
                    this.isSelf = true;
                    this.isAdmin = false;
                    myInfo().then(res => {
                        console.log(res);
                        this.userInfo = res.data;
                    }).catch( err => {
                        console.log("profile.myInfo:", err);
                    });
                } else if (this.role === 'admin' && this.$route.params.uid !== undefined) {
                    //管理员 可以更改信息 隐藏订单管理
                    this.isSelf = true;
                    this.isAdmin = true;
                    getUserInfo(this.$route.params.uid).then(res=>{
                        console.log(res);
                        this.userInfo=res.data;
                    }).catch(err=>{
                        console.log("profile.getUserInfo",err)
                    })
                } else {
                    this.isSelf = false;
                    this.isAdmin = false;
                    //否则 隐藏两个button
                    getUserInfo(this.$route.params.uid).then(res => {
                        this.userInfo = res.data;
                    }).catch( err => {
                        console.log("profile.myInfo:", err);
                    });
                }
            }
        });
    },
    computed:{
        userIcon(){
            if (this.userInfo.avatar){
                return this.GLOBAL.BASE_URL + this.userInfo.avatar;
            } else {
                return 'img/theme/team-4-800x800.jpg';
            }
        }
    },
    mounted() {
        //获取用户订单的方法
        userOrders().then(res => {
            if(res===null)
            {
                this.orders = [];
                this.successNum = 0;
                this.failNum = 0;
            }
            else
            {
                this.orders = res.data;
                this.successNum = (res.data.filter(item => item.status === "success" || item.status === "refuse" )).length;
                this.failNum = res.data.length - this.successNum;
                setStore("orders", res);
            }
        }).catch(err => {
            console.log("profile.userOrders:", err);
        });
    }
};
</script>
<style>
.custom-file-input:lang(en) ~ .custom-file-label::after {
  content: '浏览';
}
.contentDiv{
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100%;
    margin: auto;
}
</style>
